'use strict'

const Service = require('egg').Service
const jwt = require('jsonwebtoken')

class ManagerService extends Service {
  async login(userInfo) {
    let result = await this.app.mysql.query(
      'select * from c_manager where username=? and password=?',
      [userInfo.username, userInfo.password]
    )
    if (result.length > 0) {
      try {
        const token = await new Promise((resolve, reject) => {
          jwt.sign(
            {
              userid: result[0].id,
              username: result[0].username,
            },
            this.app.config.passportJwt.secret,
            {
              // token 有效时间 秒
              expiresIn: 3600,
            },
            (err, token) => {
              if (err) {
                reject(err)
              }
              resolve(token)
            }
          )
        })
        return {
          data: {
            ...result[0],
            token: 'Bearer ' + token,
          },
          meta: {
            status: 200,
            msg: '登录成功',
          },
        }
      } catch (err) {
        console.log(err)
        return {
          data: {},
          meta: {
            msg: '登录失败',
            status: 401,
          },
        }
      }
    } else {
      return {
        data: {},
        meta: {
          msg: '登录失败',
          status: 401,
        },
      }
    }
  }

  async getInfo(queryInfo) {
    // 解码token，需传加密时的 secret
    const { token } = queryInfo
    const str = token.substring(7)
    const decodeObj = jwt.verify(str, this.config.passportJwt.secret)
    // ctx.state.user = decode // 信息存一下，这步很重要，业务里要用

    let result = await this.app.mysql.query(`
  SELECT
    m.username AS username,
    r.name AS rolename 
  FROM
    c_manager AS m
  LEFT JOIN c_role AS r 
  ON m.roleid = r.id 
  WHERE
    m.username = '${decodeObj.username}'`)

    let userInfo = result[0]

    return this.ctx.getRESTfulData(userInfo, '获取用户信息成功', 200)
  }

  async logout(userInfo) {
    return this.ctx.getRESTfulData({}, '退出成功', 200)
  }
}

module.exports = ManagerService
